<template>
  <div class="admin-container" :class="{ 'dark': isDark }">
    <el-header class="header">
      <div class="header-content">
        <h2>管理员控制台</h2>
        <div class="user-info">
          <ThemeToggle />
          <span>管理员: {{ userStore.userInfo?.username }}</span>
          <el-button type="danger" link @click="handleLogout">退出登录</el-button>
        </div>
      </div>
    </el-header>

    <div class="admin-content">
      <el-tabs v-model="activeTab" @tab-click="handleTabChange">
        <el-tab-pane label="统计信息" name="statistics">
          <div class="statistics-panel" v-loading="loading.statistics">
            <el-row :gutter="20">
              <el-col :span="6" v-for="(stat, index) in statisticCards" :key="index">
                <el-card shadow="hover" class="stat-card">
                  <div class="stat-icon" :style="{background: stat.color}">
                    <el-icon><component :is="stat.icon" /></el-icon>
                  </div>
                  <div class="stat-info">
                    <div class="stat-title">{{ stat.title }}</div>
                    <div class="stat-value">{{ stat.value }}</div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="用户管理" name="users">
          <div class="users-panel" v-loading="loading.users">
            <div class="table-toolbar">
              <el-input
                v-model="userSearchKeyword"
                placeholder="搜索用户"
                class="search-input"
                clearable
                @input="filterUsers"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
              
              <el-select v-model="userRoleFilter" placeholder="角色筛选" @change="filterUsers">
                <el-option label="全部" value="" />
                <el-option label="普通用户" value="ROLE_USER" />
                <el-option label="管理员" value="ROLE_ADMIN" />
              </el-select>
            </div>
            
            <el-table :data="filteredUsers" style="width: 100%" border>
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="username" label="用户名" />
              <el-table-column prop="role" label="角色">
                <template #default="scope">
                  <el-tag :type="scope.row.role === 'ROLE_ADMIN' ? 'danger' : 'success'">
                    {{ scope.row.role === 'ROLE_ADMIN' ? '管理员' : '普通用户' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createdAt" label="创建时间" width="180">
                <template #default="scope">
                  {{ formatDate(scope.row.createdAt) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="220">
                <template #default="scope">
                  <el-button 
                    v-if="scope.row.role !== 'ROLE_ADMIN'"
                    size="small" 
                    type="primary"
                    @click="promoteUser(scope.row)"
                  >
                    设为管理员
                  </el-button>
                  <el-button 
                    v-if="scope.row.role === 'ROLE_ADMIN' && scope.row.id !== userStore.userInfo.id" 
                    size="small" 
                    type="warning"
                    @click="demoteUser(scope.row)"
                  >
                    降为普通用户
                  </el-button>
                  <el-button 
                    v-if="scope.row.id !== userStore.userInfo.id"
                    size="small" 
                    type="danger"
                    @click="deleteUser(scope.row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="查询记录" name="history">
          <div class="history-panel" v-loading="loading.history">
            <el-table :data="historyRecords.records || []" style="width: 100%" border>
              <el-table-column prop="userId" label="用户ID" width="80" />
              <el-table-column prop="inputText" label="查询需求" show-overflow-tooltip />
              <el-table-column prop="sqlResult" label="SQL结果" show-overflow-tooltip />
              <el-table-column prop="createdAt" label="创建时间" width="180">
                <template #default="scope">
                  {{ formatDate(scope.row.createdAt) }}
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 分页控件 -->
            <div class="pagination-container">
              <el-pagination
                v-if="historyRecords.total > 0"
                background
                layout="total, sizes, prev, pager, next, jumper"
                :total="historyRecords.total"
                :page-size="historyPageSize"
                :page-sizes="[10, 20, 50, 100]"
                :current-page="historyCurrentPage"
                @size-change="handleHistorySizeChange"
                @current-change="handleHistoryPageChange"
              />
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="SQL执行记录" name="executions">
          <div class="executions-panel" v-loading="loading.executions">
            <div class="statistics-cards">
              <el-card shadow="hover" class="stats-card">
                <div class="stat-value">{{ executionStats.totalExecutions || 0 }}</div>
                <div class="stat-label">总执行次数</div>
              </el-card>
              <el-card shadow="hover" class="stats-card success">
                <div class="stat-value">{{ executionStats.successfulExecutions || 0 }}</div>
                <div class="stat-label">成功执行</div>
              </el-card>
              <el-card shadow="hover" class="stats-card error">
                <div class="stat-value">{{ executionStats.failedExecutions || 0 }}</div>
                <div class="stat-label">失败执行</div>
              </el-card>
              <el-card shadow="hover" class="stats-card">
                <div class="stat-value">{{ calculateSuccessRate() }}%</div>
                <div class="stat-label">成功率</div>
              </el-card>
            </div>
            
            <div class="table-toolbar">
              <el-input
                v-model="executionSearchKeyword"
                placeholder="搜索SQL语句"
                class="search-input"
                clearable
                @input="filterExecutions"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
              
              <el-select v-model="executionStatusFilter" placeholder="执行状态" @change="filterExecutions">
                <el-option label="全部" value="" />
                <el-option label="成功" value="success" />
                <el-option label="失败" value="error" />
              </el-select>
              
              <el-select v-model="executionUserFilter" placeholder="用户筛选" @change="filterExecutions">
                <el-option label="全部用户" value="" />
                <el-option 
                  v-for="user in users" 
                  :key="user.id" 
                  :label="user.username" 
                  :value="user.id" 
                />
              </el-select>
            </div>
            
            <el-table :data="filteredExecutions" style="width: 100%" border>
              <el-table-column label="ID" prop="id" width="80" />
              <el-table-column label="用户">
                <template #default="scope">
                  <el-tooltip 
                    effect="dark" 
                    :content="getUsernameById(scope.row.userId)" 
                    placement="top"
                  >
                    <el-tag size="small">{{ getUsernameById(scope.row.userId) }}</el-tag>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column label="执行时间" width="180">
                <template #default="scope">
                  {{ formatDate(scope.row.executedAt) }}
                </template>
              </el-table-column>
              <el-table-column label="SQL语句" show-overflow-tooltip>
                <template #default="scope">
                  <el-tooltip 
                    effect="dark" 
                    :content="scope.row.sqlText" 
                    placement="top"
                    max-width="500"
                  >
                    <div class="sql-preview">{{ scope.row.sqlText }}</div>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column label="状态" width="100">
                <template #default="scope">
                  <el-tag 
                    :type="scope.row.isSuccess ? 'success' : 'danger'"
                    size="small"
                  >
                    {{ scope.row.isSuccess ? '成功' : '失败' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="rowCount" label="返回行数" width="100" />
              <el-table-column label="执行时间" width="120">
                <template #default="scope">
                  {{ formatExecutionTime(scope.row.executionTimeMs) }}
                </template>
              </el-table-column>
              <el-table-column label="数据库连接" width="150">
                <template #default="scope">
                  {{ scope.row.connectionName || '默认连接' }}
                </template>
              </el-table-column>
              <el-table-column label="错误信息" width="200" show-overflow-tooltip>
                <template #default="scope">
                  <span v-if="scope.row.errorMessage" class="error-message">
                    {{ scope.row.errorMessage }}
                  </span>
                  <span v-else>-</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="连接管理" name="connections">
          <div class="connections-panel" v-loading="loading.connections">
            <div class="table-toolbar">
              <el-input
                v-model="connectionSearchKeyword"
                placeholder="搜索连接名称/用户名"
                class="search-input"
                clearable
                @input="filterConnections"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
              
              <el-select v-model="connectionTypeFilter" placeholder="数据库类型" @change="filterConnections">
                <el-option label="全部" value="" />
                <el-option label="MySQL" value="mysql" />
                <el-option label="PostgreSQL" value="postgresql" />
                <el-option label="Oracle" value="oracle" />
                <el-option label="SQL Server" value="sqlserver" />
              </el-select>
              
              <el-select v-model="connectionUserFilter" placeholder="用户筛选" @change="filterConnections">
                <el-option label="全部用户" value="" />
                <el-option 
                  v-for="user in users" 
                  :key="user.id" 
                  :label="user.username" 
                  :value="user.id" 
                />
              </el-select>
            </div>
            
            <el-table :data="filteredConnections" style="width: 100%" border>
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="name" label="连接名称" />
              <el-table-column prop="dbType" label="数据库类型">
                <template #default="scope">
                  <el-tag :type="getDbTypeTag(scope.row.dbType)">
                    {{ scope.row.dbType.toUpperCase() }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="服务器/数据库">
                <template #default="scope">
                  {{ scope.row.host }}:{{ scope.row.port }} / {{ scope.row.databaseName }}
                </template>
              </el-table-column>
              <el-table-column label="用户">
                <template #default="scope">
                  <el-tooltip 
                    effect="dark" 
                    :content="getUsernameById(scope.row.userId)" 
                    placement="top"
                  >
                    <el-tag size="small">{{ getUsernameById(scope.row.userId) }}</el-tag>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column prop="isDefault" label="默认">
                <template #default="scope">
                  <el-tag v-if="scope.row.isDefault" type="success" size="small">默认</el-tag>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200">
                <template #default="scope">
                  <el-button-group>
                    <el-button 
                      size="small" 
                      type="primary"
                      @click="testConnection(scope.row)"
                      :loading="scope.row.testing"
                    >
                      测试
                    </el-button>
                    <el-button 
                      size="small" 
                      type="danger"
                      @click="deleteConnection(scope.row)"
                    >
                      删除
                    </el-button>
                  </el-button-group>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="系统管理" name="system">
          <div class="system-panel">
            <h3>系统维护</h3>
            
            <div class="maintenance-cards">
              <el-card shadow="hover" class="maintenance-card">
                <div class="card-header">
                  <h4>元数据缓存管理</h4>
                </div>
                <div class="card-content">
                  <p>刷新和清理系统元数据缓存，以提高系统性能。</p>
                  <div class="action-buttons">
                    <el-button 
                      type="primary" 
                      @click="refreshMetadata"
                      :loading="loading.metadataRefresh"
                    >
                      刷新元数据缓存
                    </el-button>
                    <el-button 
                      type="danger" 
                      plain
                      @click="cleanMetadata"
                      :loading="loading.metadataClean"
                    >
                      清理元数据缓存
                    </el-button>
                  </div>
                </div>
              </el-card>
              
              <el-card shadow="hover" class="maintenance-card">
                <div class="card-header">
                  <h4>系统状态</h4>
                </div>
                <div class="card-content">
                  <div class="status-items">
                    <div class="status-item">
                      <span class="label">注册用户数:</span>
                      <span class="value">{{ statistics.totalUsers }}</span>
                    </div>
                    <div class="status-item">
                      <span class="label">总查询次数:</span>
                      <span class="value">{{ statistics.totalQueries }}</span>
                    </div>
                    <div class="status-item">
                      <span class="label">总数据库连接:</span>
                      <span class="value">{{ statistics.totalConnections }}</span>
                    </div>
                  </div>
                </div>
              </el-card>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import ThemeToggle from './ThemeToggle.vue'
import { 
  Search, User, Key, Histogram, Document, 
  UserFilled, PieChart, Calendar, Monitor, 
  Connection
} from '@element-plus/icons-vue'
import { 
  getAllUsers, getUsersByRole, updateUserRole, 
  deleteUser as deleteUserApi, 
  getAllHistory, getStatistics,
  getAllDbConnections, getUserDbConnections,
  testDbConnection, toggleDbConnectionStatus,
  deleteDbConnection, getAllExecutions, getExecutionStatistics,
  refreshAllMetadata, cleanAllMetadata
} from '../api/admin'

const router = useRouter()
const userStore = useUserStore()
const isDark = ref(false)
const activeTab = ref('system')

// 加载状态
const loading = reactive({
  statistics: false,
  users: false,
  history: false,
  connections: false,
  executions: false,
  metadataRefresh: false,
  metadataClean: false
})

// 统计信息
const statistics = ref({
  totalUsers: 0,
  adminCount: 0,
  userCount: 0,
  totalQueries: 0,
  totalConnections: 0
})

const executionStats = ref({
  totalExecutions: 0,
  successfulExecutions: 0,
  failedExecutions: 0
})

const statisticCards = computed(() => [
  {
    title: '总用户数',
    value: statistics.value.totalUsers,
    icon: 'UserFilled',
    color: '#409eff'
  },
  {
    title: '管理员数',
    value: statistics.value.adminCount,
    icon: 'Key',
    color: '#f56c6c'
  },
  {
    title: '普通用户数',
    value: statistics.value.userCount,
    icon: 'User',
    color: '#67c23a'
  },
  {
    title: '查询总数',
    value: statistics.value.totalQueries,
    icon: 'Document',
    color: '#e6a23c'
  },
  {
    title: '数据库连接数',
    value: statistics.value.totalConnections || 0,
    icon: 'Monitor',
    color: '#909399'
  }
])

// 用户管理
const users = ref([])
const userSearchKeyword = ref('')
const userRoleFilter = ref('')

const filteredUsers = computed(() => {
  if (!userSearchKeyword.value && !userRoleFilter.value) return users.value
  
  return users.value.filter(user => {
    const matchKeyword = !userSearchKeyword.value || 
      user.username.toLowerCase().includes(userSearchKeyword.value.toLowerCase())
    const matchRole = !userRoleFilter.value || user.role === userRoleFilter.value
    return matchKeyword && matchRole
  })
})

// 数据库连接管理
const connections = ref([])
const connectionSearchKeyword = ref('')
const connectionTypeFilter = ref('')
const connectionUserFilter = ref('')

const filteredConnections = computed(() => {
  if (!connectionSearchKeyword.value && !connectionTypeFilter.value && !connectionUserFilter.value) 
    return connections.value
  
  return connections.value.filter(conn => {
    const matchKeyword = !connectionSearchKeyword.value || 
      conn.name.toLowerCase().includes(connectionSearchKeyword.value.toLowerCase()) ||
      getUsernameById(conn.userId).toLowerCase().includes(connectionSearchKeyword.value.toLowerCase())
    const matchType = !connectionTypeFilter.value || conn.dbType.toLowerCase() === connectionTypeFilter.value
    const matchUser = !connectionUserFilter.value || conn.userId.toString() === connectionUserFilter.value.toString()
    return matchKeyword && matchType && matchUser
  })
})

// 查询历史
const historyRecords = ref({ records: [], total: 0 })
const historyPageSize = ref(10)
const historyCurrentPage = ref(1)

// SQL执行记录相关
const executions = ref([])

// 初始化加载
onMounted(async () => {
  isDark.value = localStorage.getItem('theme') === 'dark'
  activeTab.value = 'system'
  await loadStatistics()
})

// 处理标签页变化
const handleTabChange = async (tab) => {
  if (tab.props.name === 'users' && users.value.length === 0) {
    await loadUsers()
  } else if (tab.props.name === 'history' && historyRecords.value.records.length === 0) {
    await loadHistory()
  } else if (tab.props.name === 'connections') {
    // 加载连接时也需要确保用户数据已加载
    if (users.value.length === 0) {
      await loadUsers()
    }
    if (connections.value.length === 0) {
      await loadConnections()
    }
  } else if (tab.props.name === 'executions') {
    // 加载执行记录
    if (users.value.length === 0) {
      await loadUsers()
    }
    await loadExecutions()
  } else if (tab.props.name === 'system') {
    // 加载系统管理数据
    await loadSystemData()
  }
}

// 加载统计数据
const loadStatistics = async () => {
  loading.statistics = true
  try {
    const data = await getStatistics()
    statistics.value = data
  } catch (error) {
    ElMessage.error(error.message || '获取统计信息失败')
  } finally {
    loading.statistics = false
  }
}

// 加载用户数据
const loadUsers = async () => {
  loading.users = true
  try {
    users.value = await getAllUsers()
  } catch (error) {
    ElMessage.error(error.message || '获取用户列表失败')
  } finally {
    loading.users = false
  }
}

// 加载历史记录
const loadHistory = async () => {
  loading.history = true
  try {
    const response = await getAllHistory(historyCurrentPage.value, historyPageSize.value)
    historyRecords.value = response
  } catch (error) {
    ElMessage.error(error.message || '获取历史记录失败')
  } finally {
    loading.history = false
  }
}

// 加载数据库连接
const loadConnections = async () => {
  loading.connections = true
  try {
    connections.value = await getAllDbConnections()
    // 添加临时属性用于UI状态
    connections.value.forEach(conn => {
      conn.testing = false
    })
  } catch (error) {
    ElMessage.error(error.message || '获取数据库连接失败')
  } finally {
    loading.connections = false
  }
}

// 根据用户ID获取用户名
const getUsernameById = (userId) => {
  const user = users.value.find(u => u.id === userId)
  return user ? user.username : `用户(${userId})`
}

// 获取数据库类型的标签类型
const getDbTypeTag = (dbType) => {
  const types = {
    'mysql': 'success',
    'postgresql': 'info',
    'oracle': 'warning',
    'sqlserver': 'danger'
  }
  return types[dbType.toLowerCase()] || 'info'
}

// 测试数据库连接
const testConnection = async (connection) => {
  // 设置测试中状态
  const index = connections.value.findIndex(c => c.id === connection.id)
  if (index !== -1) {
    connections.value[index].testing = true
  }
  
  try {
    await testDbConnection(connection.id)
    ElMessage.success('连接测试成功')
  } catch (error) {
    ElMessage.error(error.message || '连接测试失败')
  } finally {
    // 清除测试中状态
    if (index !== -1) {
      connections.value[index].testing = false
    }
  }
}

// 删除数据库连接
const deleteConnection = async (connection) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除连接 "${connection.name}" 吗？此操作无法撤销。`,
      '删除确认',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteDbConnection(connection.id)
    ElMessage.success('连接已删除')
    
    // 从列表中移除
    connections.value = connections.value.filter(c => c.id !== connection.id)
    
    // 更新统计数据
    statistics.value.totalConnections--
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除连接失败')
    }
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 用户搜索过滤
const filterUsers = () => {
  // 已通过computed属性实现
}

// 连接搜索过滤
const filterConnections = () => {
  // 已通过computed属性实现
}

// 提升用户为管理员
const promoteUser = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要将用户 "${user.username}" 提升为管理员吗？`,
      '角色变更确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await updateUserRole(user.id, 'ROLE_ADMIN')
    ElMessage.success('用户已提升为管理员')
    
    // 更新本地数据
    const index = users.value.findIndex(u => u.id === user.id)
    if (index !== -1) {
      users.value[index].role = 'ROLE_ADMIN'
    }
    
    // 更新统计信息
    statistics.value.adminCount++
    statistics.value.userCount--
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '角色更新失败')
    }
  }
}

// 降级管理员为普通用户
const demoteUser = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要将管理员 "${user.username}" 降级为普通用户吗？`,
      '角色变更确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await updateUserRole(user.id, 'ROLE_USER')
    ElMessage.success('管理员已降级为普通用户')
    
    // 更新本地数据
    const index = users.value.findIndex(u => u.id === user.id)
    if (index !== -1) {
      users.value[index].role = 'ROLE_USER'
    }
    
    // 更新统计信息
    statistics.value.adminCount--
    statistics.value.userCount++
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '角色更新失败')
    }
  }
}

// 删除用户
const deleteUser = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.username}" 吗？此操作将同时删除该用户的所有数据，且无法撤销。`,
      '删除确认',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'danger'
      }
    )
    
    await deleteUserApi(user.id)
    ElMessage.success('用户已删除')
    
    // 从列表中移除
    users.value = users.value.filter(u => u.id !== user.id)
    
    // 更新统计数据
    statistics.value.totalUsers--
    if (user.role === 'ROLE_ADMIN') {
      statistics.value.adminCount--
    } else {
      statistics.value.userCount--
    }
    
    // 如果当前在连接管理页面，也移除该用户的连接
    if (activeTab.value === 'connections') {
      connections.value = connections.value.filter(c => c.userId !== user.id)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除用户失败')
    }
  }
}

// 退出登录
const handleLogout = async () => {
  await userStore.logout()
  ElMessage.success('已成功退出登录')
  router.push('/login')
}

// 计算成功率
const calculateSuccessRate = () => {
  if (executionStats.value.totalExecutions === 0) return 0
  return Math.round((executionStats.value.successfulExecutions / executionStats.value.totalExecutions) * 100)
}

// 执行搜索过滤
const executionSearchKeyword = ref('')
const executionStatusFilter = ref('')
const executionUserFilter = ref('')

const filteredExecutions = computed(() => {
  if (!executions.value.length) return []
  
  return executions.value.filter(exec => {
    const matchKeyword = !executionSearchKeyword.value || 
      exec.sqlText.toLowerCase().includes(executionSearchKeyword.value.toLowerCase())
    
    const matchStatus = !executionStatusFilter.value || 
      (executionStatusFilter.value === 'success' && exec.isSuccess) ||
      (executionStatusFilter.value === 'error' && !exec.isSuccess)
    
    const matchUser = !executionUserFilter.value || 
      exec.userId.toString() === executionUserFilter.value.toString()
    
    return matchKeyword && matchStatus && matchUser
  })
})

// 格式化执行时间
const formatExecutionTime = (timeMs) => {
  if (timeMs < 1000) return `${timeMs}ms`
  const timeSec = timeMs / 1000
  if (timeSec < 60) return `${timeSec.toFixed(2)}s`
  const timeMin = timeSec / 60
  if (timeMin < 60) return `${timeMin.toFixed(2)}min`
  const timeHr = timeMin / 60
  return `${timeHr.toFixed(2)}hr`
}

// 加载执行记录
const loadExecutions = async () => {
  loading.executions = true
  try {
    // 加载执行记录
    executions.value = await getAllExecutions(200)
    
    // 加载统计数据
    executionStats.value = await getExecutionStatistics()
  } catch (error) {
    ElMessage.error(error.message || '获取SQL执行记录失败')
  } finally {
    loading.executions = false
  }
}

// 加载系统管理数据
const loadSystemData = async () => {
  // 加载系统状态数据
  if (!statistics.value.totalUsers) {
    await loadStatistics();
  }
  
  // 确保加载了用户数据，以便在统计卡片中显示
  if (users.value.length === 0) {
    await loadUsers();
  }
}

// 刷新元数据缓存
const refreshMetadata = async () => {
  loading.metadataRefresh = true
  try {
    const response = await refreshAllMetadata()
    ElMessage.success(response.message || '元数据刷新已启动')
  } catch (error) {
    ElMessage.error(error.message || '刷新元数据缓存失败')
  } finally {
    loading.metadataRefresh = false
  }
}

// 清理元数据缓存
const cleanMetadata = async () => {
  loading.metadataClean = true
  try {
    const result = await ElMessageBox.confirm(
      '确定要清理所有元数据缓存吗？这可能会暂时影响系统性能。',
      '确认操作',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await cleanAllMetadata()
    ElMessage.success(response.message || '元数据缓存已清理')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '清理元数据缓存失败')
    }
  } finally {
    loading.metadataClean = false
  }
}

// 处理历史记录分页
const handleHistorySizeChange = (size) => {
  historyPageSize.value = size
  historyCurrentPage.value = 1 // 改变每页大小时重置为第1页
  loadHistory()
}

const handleHistoryPageChange = (page) => {
  historyCurrentPage.value = page
  loadHistory()
}
</script>

<style scoped>
.admin-container {
  min-height: 100vh;
  background-color: var(--bg-color, #f5f7fa);
  color: var(--text-color, #303133);
}

.header {
  background-color: var(--card-bg, #ffffff);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
}

.header-content {
  max-width: 1400px;
  margin: 0 auto;
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.admin-content {
  max-width: 1400px;
  margin: 80px auto 0;
  padding: 24px;
}

.statistics-panel {
  margin-bottom: 24px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 16px;
  margin-bottom: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-right: 16px;
}

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-title {
  font-size: 14px;
  color: var(--text-color, #909399);
  margin-bottom: 4px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
}

.table-toolbar {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 16px;
}

.search-input {
  width: 240px;
}

.users-panel, .history-panel, .connections-panel {
  background-color: var(--card-bg, #ffffff);
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.executions-panel {
  background-color: var(--card-bg, #ffffff);
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.statistics-cards {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.stats-card {
  flex: 1;
  text-align: center;
  padding: 16px;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: var(--text-color, #909399);
}

.stats-card.success .stat-value {
  color: #67c23a;
}

.stats-card.error .stat-value {
  color: #f56c6c;
}

.sql-preview {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.error-message {
  color: #f56c6c;
}

.dark .admin-container {
  --bg-color: #1a1a1a;
  --card-bg: #2c2c2c;
  --text-color: #e0e0e0;
}

.system-panel {
  background-color: var(--card-bg, #ffffff);
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.maintenance-cards {
  display: flex;
  gap: 20px;
  margin-top: 20px;
  flex-wrap: wrap;
}

.maintenance-card {
  flex: 1;
  min-width: 300px;
}

.card-header {
  margin-bottom: 16px;
}

.card-header h4 {
  margin: 0;
  font-size: 18px;
  color: var(--text-color, #303133);
}

.card-content p {
  color: var(--text-secondary, #606266);
  margin-bottom: 16px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.status-items {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

.status-item:last-child {
  border-bottom: none;
}

.status-item .label {
  color: var(--text-secondary, #606266);
}

.status-item .value {
  font-weight: bold;
  color: var(--text-color, #303133);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.history-panel {
  padding: 16px;
  background-color: var(--card-bg, #ffffff);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style> 